import cv2 as cv
filename = r'F:\rice.png'
sourceimg = cv.imread(filename)
grayimg = cv.cvtColor(sourceimg,cv.COLOR_BGR2GRAY)   #图像灰度化
#grayimg = cv.GaussianBlur(grayimg,(7,7 ),0)
_,thresh = cv.threshold(grayimg,0,255,cv.THRESH_OTSU)  #大津分割
split = cv.getStructuringElement(cv.MORPH_CROSS,(3,3))   #形态学分开米粒
endimg = cv.morphologyEx(thresh,cv.MORPH_OPEN, split)

bin,cnts,hier = cv.findContours(endimg , cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)   #得到米粒轮廓
count = 0
for i in range(len(cnts),0,-1):    #计数和标记
    c = cnts[i-1]
    area = cv.contourArea(c)
    if area < 10:
     continue
    count = count + 1
    print("blob", i, ":", area)

    x,y,w,h = cv.boundingRect(c)
    cv.rectangle(sourceimg, (x,y), (x+w, y+h),(0,0,0xff), 1) #画框框标记在原图
    cv.putText(sourceimg, str(count), (x,y), cv.FONT_HERSHEY_PLAIN, 0.5, (0,0XFF,0))

print("number", count)
cv.imshow("source原图", sourceimg)
cv.imshow("endimg", endimg)
cv.waitKey(0)


